﻿#include <iostream>

#include "IPC.hpp"
#include "IPC2.hpp"

#include <sstream>

#if defined(_WIN32) || defined(_WIN64)
#include <Windows.h>
#endif

#if defined(__APPLPE__) || defined(__linux__) || defined(__unix__)
#include <sys/types.h>
#include <unistd.h>
#endif

struct IPC_PACKET
{
	char uuid[32];
	char name[32];
	uint32_t pid;
};

auto get_pid()
{
#if defined(_WIN32) || defined(_WIN64)
	// return ::GetProcessId(GetCurrentProcess());
	return _getpid();
#endif

#if defined(__APPLPE__) || defined(__linux__) || defined(__unix__)
	return getpid();
#endif
}

#define DEBUG_IT 1
int main(int argc, char const *argv[])
{

#if DEBUG_IT
	int mode = 1;
#else
	if (argc < 2)
	{
		std::cout << "wrong args \n";
		return 1;
	}
	int mode = atoi(argv[1]);
#endif

	auto pid = get_pid();
	std::string topic("LIVIO_SM_DEMO");

	/*
		if (mode > 0)
		{
			Publisher publisher(topic);

			IPC_PACKET pkt;
			for (int i = 0; i < 40; ++i)
			{
				pkt.pid = pid;
				auto uuid = "uuid_" + std::to_string(i + 1);
				auto name = "Name_" + std::to_string(i + 1);
				memcpy(pkt.uuid, uuid.c_str(), 32);
				memcpy(pkt.name, name.c_str(), 32);
				auto err = publisher.Publish(&pkt, sizeof(pkt));
				std::this_thread::sleep_for(std::chrono::seconds(1));
			}
			getchar();
		}
		else
		{
			Subscriber subscriber(topic);
			subscriber.BeginAutoSubscribe([pid](void *data, size_t len)
										  {
				if (data)
				{
					IPC_PACKET* pkt = (IPC_PACKET*)data;
					printf("[%d]Get New Msg, pid=%d, name=%s\n", pid, pkt->pid, pkt->name);
				} });

			getchar();
		}
	*/
	char buf[10] = {0};
	IPCChannel<IPC_PACKET> channel("LIVIO_SM_DEMO");

	if (channel.IsAttached())
	{
		if (mode > 0)
		{
			channel.BeginAutoRead([pid](const IPC_PACKET *pPkt)
								  { printf("[%d]Get Msg, pid=%d, name=%s\n", pid, pPkt->pid, pPkt->name); },
								  1);
		}
		else
		{
			IPC_PACKET pkt;
			for (int i = 0; i < 40; ++i)
			{
				pkt.pid = pid;
				auto uuid = "uuid_" + std::to_string(i + 1);
				auto name = "Name_" + std::to_string(i + 1);
				memcpy(pkt.uuid, uuid.c_str(), 32);
				memcpy(pkt.name, name.c_str(), 32);
				if (channel.SendMsg(&pkt))
					printf("[%d]Send Msg,  name = %s\n", pid, name.c_str());
			}
		}
		getchar();
	}

	return 0;
}
